/**
 * @Creator: eyes
 * @Date: 2019/12/23
 * 核心页面概览的具体内容展示组件.
 * 展示每个核心页面的首屏时间的均值、P85、P90、P95
 */

import React, {useState, useEffect} from 'react';
import echarts from 'echarts';

import {parseToWeek} from '../utils';

/**
 * 单个页面的性能图表组件. 内容包括页面信息和首屏时间的曲线图
 * @param loading{boolean} - 数据加载中
 * @param performance{[]} - 该页面的首屏时间性能数据
 */
const Page = ({loading, performance, duration}) => {
    const {label, bizName, path, data} = performance;

    // echarts图表DOM容器
    const containerId = `echarts-${bizName}-${path}`;

    // 存储echarts实例
    const [eChartsInstance, setEChartsInstance] = useState(null);

    // 根据业务数据结构生成echarts需要的数据结构(Option)
    const generateOption = data => (
        {
            legend: {
                bottom: 10,
                left: 'center',
                selected: {
                    '均值': false,
                    '85th': false,
                    '90th': true,
                    '95th': true

                }
            },
            grid: {
                top: 20,
                left: 80,
            },
            tooltip: {
                trigger: 'axis',
                formatter(param) {
                    if (duration === 10) {
                        const htmlChunk =  param.map((item, index) => {
                            let endTime = '';
                            const tempMin = Number(item.name.substring(item.name.length - 2)) + 10;
                            const tempHour = (Number(item.name.substring(0, 2)) + 1)
                                .toString().padStart(2, '0');
                            if (tempMin === 60) {
                                endTime = `${tempHour}: 00`;
                            }
                            else {
                                endTime = `${item.name.substring(0, 2)}:${tempMin}`;
                            }
                            let chunk = `${item.marker}${item.seriesName}: `;
                            if (item.seriesName === '均值') {
                                chunk += `${item.value[1]}<br/>`;
                            }
                            if (item.seriesName === '85th') {
                                chunk += `${item.value[2]}<br/>`;
                            }
                            if (item.seriesName === '90th') {
                                chunk += `${item.value[3]}<br/>`;
                            }
                            if (item.seriesName === '95th') {
                                chunk += `${item.value[4]}<br/>`;
                            }
                            return index === 0
                                ? (
                                    `[${item.name}, ${endTime})<br/>${chunk}`
                                ) : `${chunk}`;
                        });
                        return htmlChunk.join('');
                    }
                    const htmlChunk = param.map((item, index) => {
                        if (item.seriesName === '均值') {
                            return `${item.marker}${item.seriesName}: ${item.value[1]}<br/>`;
                        }
                        if (item.seriesName === '85th') {
                            return `${item.marker}${item.seriesName}: ${item.value[2]}<br/>`;
                        }
                        if (item.seriesName === '90th') {
                            return `${item.marker}${item.seriesName}: ${item.value[3]}<br/>`;
                        }
                        if (item.seriesName === '95th') {
                            return `${item.marker}${item.seriesName}: ${item.value[4]}<br/>`;
                        }
                        return null;

                    });
                    return `${param[0].name} ${parseToWeek(param[0].name)}<br/>${htmlChunk.join('')}`;
                }
            },
            dataset: {
                source: data.map(_ =>
                    ['datetime', 'targetAvg', 'target85th', 'target90th', 'target95th'].map(key => _[key])),
            },
            xAxis: {
                type: 'category',
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter(val) {
                        if (val > 0) {
                            return `${val}ms`;
                        }
                        return val;
                    }
                }
            },
            series: ['均值', '85th', '90th', '95th'].map((key, index) => (
                {
                    type: 'line',
                    smooth: true,
                    encode: {
                        x: 0,
                        y: index + 1,
                    },
                    name: key,
                }
            )),
        }
    );

    // echarts初始化的effect
    useEffect(() => {
        const chartsContainer = echarts.init(document.getElementById(containerId));

        setEChartsInstance(chartsContainer);

        if (data) {
            chartsContainer.setOption(generateOption(data), true);
        }

        window.addEventListener('resize', chartsContainer.resize);
    }, []);

    // echarts更新的effect
    useEffect(() => {
        if (data && eChartsInstance) {
            eChartsInstance.setOption(generateOption(data), true);
        }
    }, [data]);

    // 设置loading状态
    useEffect(() => {
        if (eChartsInstance) {
            loading
                ? eChartsInstance.showLoading()
                : eChartsInstance.hideLoading();
        }
    }, [loading, eChartsInstance]);

    return (
        <div className="page-graph-container">
            <div className="page-info">
                <span className="page-title">
                    {label}
                </span>
                <span className="page-path">
                    {path}
                </span>
            </div>
            <div className="page-graph" id={containerId} style={{paddingLeft: '12px'}} >
            </div>
        </div>
    );
};

export default props => {
    const {loading, performances, duration} = props;
    return !!performances
        && !!performances.length
        && performances.map(performance => (
            <Page
                key={performance.bizName + performance.path}
                loading={loading} performance={performance}
                duration={duration}
            />
        ));
};
